package com.skyline.user.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.imagine.core.ResultState;
import net.imagine.provider.skyline.ImageCropResult;
import net.imagine.provider.skyline.ImageCutter;
import net.imagine.provider.skyline.SkylineImageCropTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.skyline.base.controller.BaseController;
import com.skyline.base.exception.NotLoginException;
import com.skyline.base.exception.OperateFailedException;
import com.skyline.common.util.Constant;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.user.model.User;
import com.skyline.user.service.PersonalInfoService;
import com.skyline.user.type.Sex;
import com.skyline.wo.model.Album;
import com.skyline.wo.model.Photo;
import com.skyline.wo.service.AlbumService;

@RequestMapping("/user")
@Controller
public class PersonalInfoController extends BaseController {
	private static final Log LOGGER = LogFactory.getLog(PersonalInfoController.class);
	@Autowired
	private PersonalInfoService personalInfoService;

	/**
	 * User user = (User) WebHelper.getSessionAttribute(null,
	 * Constant.SESSION_USER); /user/completePersonalInfo
	 * */
	// @Autowired
	// private PersonalInfoService personalInfoUserService;
	@Autowired
	private AlbumService albumService;

	@Autowired
	private ImageCutter crop;
	@Value("${imagine.protraitSize}")
	private int portraitSize;
	@Value("${imagine.localStorePath}")
	private String basePath;

//	@Value("${view.user.completePersonalInfo}")
//	private String completePersonalInfoView;
//
//	@Value("${view.user.updatePersonalInfo}")
//	private String updatePersonalInfoView;
//	@Value("${view.user.uploadphoto}")
//	private String photoUploadView;
//
//	private @Value("${view.user.login}")
//	String loginView;

	@RequestMapping("/complete")
	//FIXME 不要返回String
	public String completePersonInfoRequest() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		user = personalInfoService.getPersonInfoByUserID(user.getId());

		WebHelper.initRequest(null).setAttribute("personalInfo", user);
		WebHelper.initRequest(null).setAttribute("personalInfo_sex_name", user.getSex().name());
		return ViewPaths.USER_COMPLETEPERSONALINFO;
	}

	@RequestMapping(value = "/updateinfo", method = RequestMethod.GET)
	public ModelAndView updatePersonInfoRequest() {
		ModelAndView v = new ModelAndView();
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		try {
			user = personalInfoService.getPersonInfoByUserID(user.getId());
			WebHelper.initRequest(null).setAttribute("personalInfo", user);
			v.setViewName(ViewPaths.USER_UPDATEPERSONALINFO);
			return v;
		} catch (Exception e) {
			e.printStackTrace();
			v.setViewName(ViewPaths.USER_LOGIN);
			return v;
		}
	}

	/**
	 * updatePersonInfo() 对用户输入的信息进行验证，施行登陆
	 */
	@RequestMapping(value = "/updateinfo", method = RequestMethod.POST)
	public ModelAndView updatePersonInfo(String name, String nickname, Sex sex,
			String graduateshool, String job, String msn, String qq, String mobilephone,
			String country, String province, String city, String birthday) {
		ModelAndView v = new ModelAndView();
		// String ip = httpServletRequest.getRemoteAddr();
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);

		String countryName = country.split("-")[0];
		String provinceName = province.split("-")[0];
		String cityName = city.split("-")[0];
		String siteId = city.split("-")[1];

		try {
			// Date updateTime = new Date();
			Date dDate = null;
			try {
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				dDate = format.parse(birthday);
				// return dDate;
			} catch (Exception e) {
				// Date now = new Date();
				dDate = new Date();
				// return now;
			}
			personalInfoService.modifyBasicInfo(user.getId(), name, nickname, dDate, sex,
					provinceName, cityName, countryName, siteId, job, graduateshool);
			personalInfoService.modifyCommunicationInfo(user.getId(), mobilephone, msn, qq);
			user = personalInfoService.getPersonInfoByUserID(user.getId());
			WebHelper.initRequest(null).setAttribute("personalInfo", user);
			// httpServletRequest.setAttribute("personalInfo_sex_name",
			// user.getSex().name());
			v.setViewName(ViewPaths.USER_UPDATEPERSONALINFO);
			return v;
		} catch (Exception e) {
			e.printStackTrace();
			v.setViewName(ViewPaths.USER_LOGIN);
			v.addObject("email", name);
			return v;
		}
	}

	@RequestMapping(value = "/photoupload", method = RequestMethod.GET)
	public ModelAndView photoUploadRequest() {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			throw new NotLoginException("上传头像必须登录");
		}

		long ownerId = user.getId();
		Album portraitAlbum = albumService.getUserPortraitAlbum(ownerId);
		Photo portraitPhoto = albumService.getCurrentPortraitPhotoFromAlbum(portraitAlbum);

		ModelAndView view = new ModelAndView();
		view.addObject("portraitAlbum", portraitAlbum);
		view.addObject("portrait", portraitPhoto);
		view.setViewName(ViewPaths.USER_UPLOADPHOTO);
		return view;
	}

	@RequestMapping(value = "/photoupload", method = RequestMethod.POST)
	public ModelAndView photoUploadOk(Integer x, Integer y, Integer size, String submitToken) {
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (user == null) {
			throw new NotLoginException("上传头像必须登录");
		}

		String errMsg = this.validateForm("portraitUploadForm", submitToken);
		if (errMsg != null) {
			return processValidationErrors("errMsg", errMsg, photoUploadRequest());
		}

		long ownerId = user.getId();
		Photo portrait = albumService.getUserCurrentPortraitPhoto(ownerId);
		if (portrait == null) {
			throw new OperateFailedException("不存在当前图片，无法剪切");
		}
		long albumId = portrait.getAlbumId();

		String smallFile = portrait.getSmallFile();
		String ext = portrait.getExt();
		String remoteFileKey = smallFile + '.' + ext;

		SkylineImageCropTask cropTask = new SkylineImageCropTask(remoteFileKey, portraitSize);
		cropTask.setAlbumId(albumId);
		cropTask.setUserId(ownerId);
		cropTask.setOffsetX(x);
		cropTask.setOffsetY(y);
		cropTask.setCropSize(size);
		ImageCropResult cropResult;
		try {
			cropResult = crop.processImage(basePath, cropTask);
		} catch (IOException e) {
			throw new OperateFailedException("无法剪切图片");
		}
		if (cropResult == null || cropResult.getResultState() != ResultState.SUCCESS) {
			throw new OperateFailedException("无法剪切图片，原因："
					+ (cropResult == null ? null : cropResult.getResultState()));
		}
		String portraitFile = cropResult.getFileKey();

		personalInfoService.changeUserPortrait(ownerId, portraitFile);
		user.setPortrait(portraitFile);
		WebHelper.setSessionAttribute(null, Constant.SESSION_USER, user);

		String url = buildRecirectPath("/wo/myWo");
		ModelAndView view = new ModelAndView(new RedirectView(url));
		return view;
	}

	// //使用springMVC返回JSON对于FireFox下会变成下载链接，有BUG，不能使用
	// @RequestMapping(value = "/upload", method = RequestMethod.POST)
	// public @ResponseBody Map<String, Object>
	// uploadPicture(@RequestParam("file") MultipartFile file) {
	// User user = (User) WebHelper.getSessionAttribute(null,
	// Constant.SESSION_USER);
	// Map<String, Object> result = new HashMap<String, Object>();
	// if (user == null) {
	// result.put("success", Boolean.FALSE);
	// result.put("errmsg", "修改照片描述必须登录");
	// result.put("logined", Boolean.FALSE);
	// return result;
	// }
	// result.put("logined", Boolean.TRUE);
	// try {
	// result.put("success", Boolean.TRUE);
	// result.put("errmsg", "上传头像成功");
	// return result;
	// } catch (Exception e) {
	// LOGGER.warn("上传头像失败",e);
	// result.put("success", Boolean.FALSE);
	// result.put("errmsg", "上传头像失败，请稍候重试");
	// return result;
	// }
	// // try {
	// // List<MultipartFile> files = request.getFiles("file");
	// // System.out.println(files.get(0).getOriginalFilename());
	// // map.put("imgsrc", user.getId().toString() + files.get(0).getName());
	// // return map;
	// // } catch (Exception e) {
	// // e.printStackTrace();
	// // return null;
	// // }
	//
	// }

	@RequestMapping(value = "/modifypassword", method = RequestMethod.POST)
	public @ResponseBody
	Boolean modifyPassword(@RequestParam("oldPassword") String oldPassword,
			@RequestParam("password") String password,
			@RequestParam("passwordConfirm") String passwordConfirm) {
		// String ip = httpServletRequest.getRemoteAddr();
		try {
			User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
			// Date updateTime = new Date();
			if (personalInfoService.checkPassword(user.getId(), oldPassword)) {
				personalInfoService.updatePassword(user.getId(), passwordConfirm);
			}
			return personalInfoService.checkPassword(user.getId(), password);
		} catch (Exception e) {
			LOGGER.warn("修改密码失败",e);
			return false;
		}
	}

	@RequestMapping("/checkoldpassword/{password}")
	@ResponseBody
	public Boolean checkOldPassword(@PathVariable String password) {
		try {
			User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
			return personalInfoService.checkPassword(user.getId(), password);
		} catch (Exception e) {
			LOGGER.warn("检查密码是否匹配失败",e);
			return false;

		}
	}
}
